package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"school-repo/cache"
	"school-repo/model"
	"time"
)

func ArticleAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	anchor := c.PostForm("anchor")

	article := model.Article{
		Title:   title,
		Content: content,
		Anchor:  anchor,
	}

	redis_key := "article_add_"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		model.DB.Create(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": article,
	})
}

func ArticleDel(c *gin.Context) {
	id := c.PostForm("id")

	redis_key := "article_del_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	err := model.DB.Where("id=?", id).Delete(&model.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func ArticleList(c *gin.Context) {
	var article []model.Article
	redis_key := "article_list"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		model.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": article,
	})
	return

}

func ArticleDetail(c *gin.Context) {
	id := c.Query("id")

	var article []model.Article
	redis_key := "article_list" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		model.DB.Where("id=?", id).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": article,
	})
	return
}
